<template>
    <div>
        <el-container class="home-container">
            <el-container>
                <!-- 主体部分 -->
                <el-main>
                    <div style="width: 80%; margin: 0 auto">
                        <el-row>
                            <!-- 左侧信息展示 -->
                            <el-col :span="6">
                                <div class="grid-content bg-purple">
                                    <span class="el-dropdown-link">
                                      <div style="margin-top: 50px"/>
                                        <!-- 用户头像 -->
                                      <el-avatar :src="userAvatar" :size="200"></el-avatar>
                                      <div style="height: 30px"></div>
                                        <!-- 上传头像 -->
                                      <el-upload
                                              class="avatar-uploader"
                                              :headers="headers"
                                              action="http://localhost:12188/ss/user/upload"
                                              :show-file-list="false"
                                              :on-success="handleAvatarSuccess"
                                              :on-error="handleAvatarError"
                                              :before-upload="beforeAvatarUpload"
                                      >
                                        <el-button size="small" type="primary">
                                          点击更改头像
                                        </el-button>
                                        <div slot="tip" class="el-upload__tip">
                                          只能上传JPG/GIF/PNG/BMP文件，且不超过2M
                                        </div>
                                      </el-upload>
                                    </span>
                                </div>
                            </el-col>
                            <!-- 右侧信息展示 -->
                            <el-col :span="18">
                                <div class="grid-content bg-purple-light" style="text-align: left; padding-left: 50px">
                                    <b>账户信息</b>
                                    <el-card class="box-card">
                                        <div class="text item">
                                            <el-row>
                                                <el-col :span="4" style="text-align: right">
                                                    <div class="grid-content bg-purple">登录名称：</div>
                                                </el-col>
                                                <el-col :span="20">
                                                    <div class="grid-content bg-purple-light">
                                                        {{ cardData.loginName }}
                                                        <el-link
                                                                style="float: right"
                                                                type="primary"
                                                                icon="el-icon-edit"
                                                                @click="showUpdateUserInfoForm"
                                                        >修改信息
                                                        </el-link
                                                        >
                                                    </div>
                                                </el-col>
                                            </el-row>
                                            <el-row>
                                                <el-col :span="4" style="text-align: right">
                                                    <div class="grid-content bg-purple">用户名：</div>
                                                </el-col>
                                                <el-col :span="20">
                                                    <div class="grid-content bg-purple-light">
                                                        {{ cardData.userName }}
                                                    </div>
                                                </el-col>
                                            </el-row>
                                            <el-row>
                                                <el-col :span="4" style="text-align: right">
                                                    <div class="grid-content bg-purple">邮箱：</div>
                                                </el-col>
                                                <el-col :span="20">
                                                    <div class="grid-content bg-purple-light">
                                                        {{ cardData.email }}
                                                    </div>
                                                </el-col>
                                            </el-row>
                                            <el-row>
                                                <el-col :span="4" style="text-align: right">
                                                    <div class="grid-content bg-purple">电话号码：</div>
                                                </el-col>
                                                <el-col :span="20">
                                                    <div class="grid-content bg-purple-light">
                                                        {{ cardData.phonenumber }}
                                                    </div>
                                                </el-col>
                                            </el-row>
                                            <el-row>
                                                <el-col :span="4" style="text-align: right">
                                                    <div class="grid-content bg-purple">性别：</div>
                                                </el-col>
                                                <el-col :span="20">
                                                    <div class="grid-content bg-purple-light">
                                                        {{ cardData.sex == "0" ? "男" : "女" }}
                                                    </div>
                                                </el-col>
                                            </el-row>
                                        </div>
                                    </el-card>
                                </div>
                            </el-col>
                        </el-row>
                        <!--修改密码-->
                        <el-row>
                            <el-col :push="6" :span="18">
                                <div class="grid-content bg-purple-light" style="text-align: left; padding-left: 50px">
                                    <b>修改密码</b>
                                    <el-card class="box-card">
                                        <el-form :model="passForm" status-icon :rules="passRules" ref="passForm"
                                                 label-width="100px" class="demo-passForm" style="width: 500px">
                                            <el-input style="display:none;" v-model="passForm.username"/>
                                            <el-form-item label="旧密码" prop="oldPassword">
                                                <el-input  type="password" v-model.number="passForm.oldPassword"></el-input>
                                            </el-form-item>
                                            <el-form-item label="新密码" prop="newPassword">
                                                <el-input type="password" v-model="passForm.newPassword"
                                                          autocomplete="off"></el-input>
                                            </el-form-item>
                                            <el-form-item label="确认密码" prop="newPassword2">
                                                <el-input type="password" v-model="passForm.newPassword2"
                                                          autocomplete="off"></el-input>
                                            </el-form-item>
                                            <el-form-item>
                                                <el-button type="primary" @click="submitForm('passForm')">提交</el-button>
                                                <el-button @click="resetForm('passForm')">重置</el-button>
                                            </el-form-item>
                                        </el-form>
                                    </el-card>
                                </div>
                            </el-col>
                        </el-row>
                    </div>
                    <!--修改个人信息弹出框-->
                    <el-dialog title="个人信息修改" :visible.sync="dialogFormVisible" width="500px">
                        <el-form :model="form" :rules="rules" ref="form">
                            <el-form-item
                                    prop="username"
                                    label="登录名称"
                                    :label-width="labelWidth"
                            >
                                <el-input v-model="form.loginName" autocomplete="off"></el-input>
                            </el-form-item>
                            <el-form-item label="用户名" :label-width="labelWidth">
                                <el-input v-model="form.userName" autocomplete="off"></el-input>
                            </el-form-item>
                            <el-form-item prop="email" label="邮箱" :label-width="labelWidth">
                                <el-input v-model="form.email" autocomplete="off"></el-input>
                            </el-form-item>
                            <el-form-item
                                    prop="phonenumber"
                                    label="电话号码"
                                    :label-width="labelWidth"
                            >
                                <el-input
                                        v-model="form.phonenumber"
                                        autocomplete="off"
                                ></el-input>
                            </el-form-item>
                            <el-form-item
                                    label="性别"
                                    :label-width="labelWidth"
                                    style="text-align: left"
                            >
                                <el-radio v-model="form.sex" label="0">男</el-radio>
                                <el-radio v-model="form.sex" label="1">女</el-radio>
                            </el-form-item>
                        </el-form>
                        <div slot="footer" class="dialog-footer">
                            <el-button @click="dialogFormVisible = false">取 消</el-button>
                            <el-button type="primary" @click="updatePersonInfoSubmit()">确 定</el-button>
                        </div>
                    </el-dialog>
                </el-main>
            </el-container>
        </el-container>
    </div>
    <!-- 弹出框修改用户信息 -->
</template>

<script>
    export default {

        data() {
            var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else {
                    if (this.passForm.newPassword !== '') {
                        this.$refs.passForm.validateField('checkPass');
                    }
                    callback();
                }
            };
            var validatePass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.passForm.newPassword) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
            return {
                username: window.localStorage.getItem("username"),
                userAvatar: '',

                // 卡片中展示的数据
                cardData: {},
                // 修改密码表单的数据
                passForm: {
                    username: '',
                    oldPassword: '',
                    newPassword: '',
                    newPassword2: ''
                },
                // 表单是否显示
                dialogFormVisible: false,
                // 修改用户信息表单
                form: {},
                labelWidth: "100px",
                // 上传头像的请求头
                headers: {
                    myAuthorization: window.localStorage.getItem("token"),
                },
                // 修改基本信息表单验证规则
                rules: {
                    username: [
                        {required: true, message: "请输入登录名称", trigger: "blur"},
                        {
                            min: 3,
                            max: 20,
                            message: "长度在 3 到 20 个字符",
                            trigger: "blur",
                        },
                    ],
                    email: [
                        {required: true, message: "请输入邮箱地址", trigger: "blur"},
                        {
                            type: "email",
                            message: "邮箱格式不正确",
                            trigger: ["blur", "change"],
                        },
                    ],
                    phonenumber: [
                        {required: true, message: "请输入手机号码", trigger: "blur"},
                        {min: 11, max: 11, message: "手机号格式不正确", trigger: "blur"},
                    ],
                },
                passRules: {
                    newPassword: [
                        {validator: validatePass, trigger: 'blur'}
                    ],
                    newPassword2: [
                        {validator: validatePass2, trigger: 'blur'}
                    ],
                }
            };
        },

        created() {
            this.initThisPage();
        },

        methods: {
            // 初始化页面信息
            async initThisPage() {
                let id = localStorage.getItem("id")
                // 请求用户信息
                let res = await this.$http.get("/ss/user/selectOne?id=" + id);
                this.cardData = res.data.t;
                this.userAvatar = this.cardData.avatar;
                this.passForm.username = this.cardData.userName
            },

            // 修改用户信息
            showUpdateUserInfoForm() {
                // 修改信息的表单显示出来
                this.dialogFormVisible = true;
                // 初始化表单数据
                this.form = this.cardData;

            },

            // 提交用户修改的信息
            async updatePersonInfoSubmit() {
                this.$http.put("/ss/user/update", this.form).then(res => {
                    if (Number(res.data.resultCode) === 2000) {
                        this.$message({type: 'success', message: '恭喜你，修改成功'});
                        this.dialogVisible = false;
                    } else {
                        this.$message({type: 'error', message: '系统异常'});
                    }

                });
                this.dialogFormVisible = false; // 关闭表单
            },

            // 上传之前的调用
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isGIF = file.type === 'image/gif';
                const isPNG = file.type === 'image/png';
                const isBMP = file.type === 'image/bmp';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG && !isGIF && !isPNG && !isBMP) {
                    this.common.errorTip('上传图片必须是JPG/GIF/PNG/BMP 格式!');
                }
                if (!isLt2M) {
                    this.common.errorTip('上传图片大小不能超过 2MB!');
                }
                return (isJPG || isBMP || isGIF || isPNG) && isLt2M;
            },

            // 上传成功之后调用
            async handleAvatarSuccess(res, file) {
                console.log(res)
                // 如果更新成功则更新数据库中的头像地址
                if (Number(res.resultCode) === 2000) {
                    this.userAvatar = res.t;
                    window.localStorage.setItem("avatar", res.t);
                    this.$http.put("/ss/user/update",{userId: this.cardData.userId, avatar: this.userAvatar}
                    ).then(res => {
                        if (Number(res.data.resultCode) === 2000) {
                            this.$message.success("上传头像成功");
                        }
                    });

                } else {
                    this.$message.error("上传失败，请稍后重试");
                }
            },

            // 上传失败之后调用
            handleAvatarError(res, file) {
                console.log(res)
                this.$message.error("上传失败，请换一张图片再次尝试");
            },

            // 修改密码表单提交
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.$http.get("/sso/userLogin/updateUserPassword?userName=" +
                            this.passForm.username + "&oldPassword=" + this.passForm.oldPassword + "&newPassword=" + this.passForm.newPassword).then(res => {
                                if (res.data.t === true) {
                                    this.$message({type: 'success', message: '修改成功，需要重新登录'});
                                    this.$router.push('/')
                                } else {
                                    this.$message({type: 'error', message: '旧密码错误'});
                                }
                            })
                    } else {
                        return false;
                    }
                });
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            }
        }
    };
</script>

<style scoped>
    .home-container {
        height: 100%;
    }

    .el-header > div {
        display: flex;
        align-items: center;
    }

    .el-header > div > span {
        margin-left: 15px;
    }

    .el-aside {
        background-color: #333744;
    }

    .el-aside .el-menu {
        border: none;
    }

    .el-main {
        background-color: #eaedf1;
    }

    .toggle {
        background-color: #4a5064;
        color: #fff;
        line-height: 24px;
        font-size: 10px;
        text-align: center;
        letter-spacing: 5px;
        cursor: pointer;
    }

    /* 卡片内容样式 */
    .text {
        font-size: 14px;
    }

    .item {
        padding: 18px 0;
    }

    .el-row {
        margin-bottom: 20px;
    }
</style>